package com.lonely.common.utils;

import cn.dev33.satoken.secure.SaSecureUtil;
import com.lonely.common.constant.HttpStatus;
import com.lonely.common.core.domain.auth.LoginUser;
import com.lonely.common.exception.AuthException;
import com.lonely.common.threadlocals.LoginUserThreadLocal;
import com.lonely.common.utils.spring.SpringUtils;
import lombok.extern.slf4j.Slf4j;

/**
 * 安全服务工具类
 *
 * @author fzzf
 */
@Slf4j
public class SecurityUtils {


    /**
     * 获取登录用户id
     *
     * @return
     */
    public static Long getUserId() {
        try {
            return getLoginUser().getUser().getUserId();
        } catch (Exception e) {
            log.error("获取用户id异常", e);
            throw new AuthException("获取用户id异常", HttpStatus.UNAUTHORIZED);
        }
    }


    /**
     * 获取登录用户对应的工厂id
     *
     * @return
     */
    public static Long getFactoryId() {
        try {
            return getLoginUser().getUser().getFactoryId();
        } catch (Exception e) {
            log.error("获取登录用户对应的工厂id异常", e);
            throw new AuthException("获取登录用户对应的工厂id异常", HttpStatus.UNAUTHORIZED);
        }
    }

    /**
     * 获取用户账户
     **/
    public static String getUsername() {
        try {
            return getLoginUser().getUsername();
        } catch (Exception e) {
            throw new AuthException("获取用户账户异常", HttpStatus.UNAUTHORIZED);
        }
    }

    /**
     * 获取用户
     **/
    public static LoginUser getLoginUser() {

        // 先尝试从thread local中获取，如果获取不到，则调用tokenService
        LoginUser loginUser = LoginUserThreadLocal.getLoginUser();
        if (loginUser != null) {
            return loginUser;
        }

        TokenService1 tokenService = SpringUtils.getBean(TokenService1.class);
        try {
            return tokenService.getLoginUser();
        } catch (Exception e) {
            log.error("获取用户信息异常", e);
            throw new AuthException("获取用户信息异常", HttpStatus.UNAUTHORIZED);
        }
    }

    /**
     * 生成BCryptPasswordEncoder密码
     *
     * @param password 密码
     * @return 加密字符串
     */
    public static String encryptPassword(String password) {
        return SaSecureUtil.sha256(password);
    }

    public static void main(String[] args) {
        System.out.println(encryptPassword("1111"));
    }

    /**
     * 判断密码是否相同
     *
     * @param rawPassword     真实密码
     * @param encodedPassword 加密后字符
     * @return 结果
     */
    public static boolean matchesPassword(String rawPassword, String encodedPassword) {
        String encryptedPassword = encryptPassword(rawPassword);
        return StringUtils.equals(encryptedPassword, encodedPassword);
    }

    /**
     * 是否为管理员
     *
     * @param userId 用户ID
     * @return 结果
     */
    public static boolean isAdmin(Long userId) {
        return userId != null && 1L == userId;
    }
}
